﻿namespace Baggr.ClientSite.Models
{
    using System;
    using System.Linq;

    /// <summary>
    /// Model, where feed items sorted and filtered by data passed from query.
    /// </summary>
    public class FilteredAndSortedFeed
    {
        private readonly FeedDataContext _DataContext;
        private readonly User _User;
        private readonly Feed _Feed;
        private readonly FeedItemsFilter _Filter;
        private readonly FeedItemsSorting _Sorting;

        /// <summary>
        /// Class constructor.
        /// </summary>
        /// <param name="dataContext">
        /// linq to SQL data context.
        /// </param>
        /// <param name="user">
        /// Querying user.
        /// </param>
        /// <param name="feed">
        /// Querying feed
        /// </param>
        /// <param name="filter">
        /// Filter for use in query to database.
        /// </param>
        /// <param name="sorting">
        /// Sort order for use in query to database.
        /// </param>
        public FilteredAndSortedFeed(
            FeedDataContext dataContext,
            User user,
            Feed feed,
            FeedItemsFilter filter,
            FeedItemsSorting sorting)
        {
            if (dataContext == null) throw new ArgumentNullException("dataContext");
            if (user == null)
                throw new ArgumentNullException("user");
            if (feed == null)
                throw new ArgumentNullException("feed");
            if (filter == null)
                throw new ArgumentNullException("filter");
            if (sorting == null)
                throw new ArgumentNullException("sorting");
            _DataContext = dataContext;
            _User = user;
            _Feed = feed;
            _Filter = filter;
            _Sorting = sorting;
        }

        public FeedItemsSorting Sorting
        {
            get { return _Sorting; }
        }

        public FeedDataContext DataContext
        {
            get { return _DataContext; }
        }

        public User User
        {
            get { return _User; }
        }

        public Feed Feed
        {
            get { return _Feed; }
        }

        public FeedItemsFilter Filter
        {
            get { return _Filter; }
        }

        public IOrderedEnumerable<FeedItem> Items
        {
            get
            {
                var result = (from feed in Feed.Items
                    where Filter.IsShowUnreaded ? !DataContext.IsFeedRead(User.UserId, feed.Id).Value : true
                    orderby feed.Date descending
                    select feed);
                if (Sorting.IsByRating)
                    result = result.OrderByDescending(curr => curr.Rate ?? 0);
#warning Не готова сортировка по релевантности.
                return result;
            }
        }
    }
}
